<?php

namespace App\Http\Controllers\Article\Web;

use App\Enums\WorkOrder\OrderEnum;
use App\Http\Controllers\BaseController;
use App\Jobs\Export\Export;
use App\Models\Article\ArticleModel;
use App\Service\Article\ArticleOperateService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ArticleStatisticsController extends BaseController
{

    /**
     * 数据统计列表
     * @param Request $request
     * @return JsonResponse
     */
    public function list(Request $request): JsonResponse
    {
        return $this->success(ArticleOperateService::statisticsTotal());
    }


    /**
     * 文章列表
     * @param Request $request
     * @return JsonResponse
     */
    public function articleList(Request $request): JsonResponse
    {
        $type     = (int)$request->get('type', 0);   //内容分类 1 - 文章  2 - 视频
        $hotType  = (int)$request->get('hotType', 0);//热门分类排序字段  1 - 点赞  2 - 收藏
        $pageSize = (int)$request->get('pageSize', 20);
        $pageNum  = (int)$request->get('pageNum', 1);
        return $this->success(ArticleOperateService::articleList($type, $hotType, $pageSize, $pageNum));
    }


    /**
     * 文章数据统计列表
     * @param Request $request
     * @return JsonResponse
     */
    public function getArticleList(Request $request): JsonResponse
    {
        $this->validate(
            $request, [
                'id'                 => 'required|integer',
                'statisticalStartAt' => 'required|date',
                'statisticalEndAt'   => 'required|date',
            ]
        );
        $id                 = (int)$request->get('id', 0);
        $statisticalStartAt = (string)$request->get('statisticalStartAt', '');
        $statisticalEndAt   = (string)$request->get('statisticalEndAt', '');
        $export             = (bool)$request->get('export', 0);

        if ($export) {
            if ($id > 0) {
                $exportType     = Export::TYPE_ARTICLE_SINGLE_ANALYSIS;
                $articleModel   = ArticleModel::query()->where("id", $id)->first();
                $fileNamePrefix = "单篇分析-" . attributeGet($articleModel, "title", "单篇");
            } else {
                $exportType     = Export::TYPE_ARTICLE_HOLISTIC_ANALYSIS;
                $fileNamePrefix = "整体分析-整体";
            }

            dispatch(
                (new Export(
                    "{$fileNamePrefix}-{$statisticalStartAt}-{$statisticalEndAt}",
                    $exportType,
                    [
                        'data'   => $request->all(),
                        'userId' => getRmsUserId(),
                        'id'     => $id
                    ]
                ))
            )->onQueue(Export::QUEUE_NAME);
            return $this->success([]);
        }

        return $this->success(ArticleOperateService::getArticleList($id, $statisticalStartAt, $statisticalEndAt));
    }
}
